package ca.etsmtl.log320lab1;

import java.util.ArrayList;

public class Huffman {
	protected int[] _FrequencyTable;
	protected int[] _EncodeTable;
	protected String[] codes = new String[256];
	public Huffman(int[] frequencyTable)
	{
		_FrequencyTable = frequencyTable;
		_EncodeTable = new int[frequencyTable.length];
	}
	public String[] build()
	{
		// Heap heap = new Heap(256);
		ArrayList<CharFrequency> list = new ArrayList<CharFrequency>();
		for (int i = 0; i < _FrequencyTable.length; i++) {
			int frequency = _FrequencyTable[i];
			if (frequency != 0)
			{
					list.add(new CharFrequency(i,frequency));
			}
		}
		Heap.heapSort(list);
		CharFrequency ParentNode = null;
		while (list.size() >= 2) {
			ParentNode = new CharFrequency(true,list.get(list.size() - 2), list.get(list.size() - 1));
			list.remove(list.size() -1);
			list.set(list.size() -1 , ParentNode);
			Heap.heapSort(list);
		}
		if (ParentNode == null && list.size() == 1) {
			ParentNode = new CharFrequency(true,null,list.get(0));
		}
 	    BuildEncryptionCode(ParentNode);
		return codes;
				
	}
	private void BuildEncryptionCode(CharFrequency node)
	{
		if (!node.getIsParentNode()) {
			codes[node._character] = node.getEncryptionCode();
			return;
		}
		if (node.getLeftChild() != null) {
			node.getLeftChild().setEncryptionCode(node.getEncryptionCode() + "0"); // Code du left
			BuildEncryptionCode(node.getLeftChild()); // appel par recurrence
		}
		if (node.getRightChild() != null) {
			node.getRightChild().setEncryptionCode(node.getEncryptionCode() + "1"); // Code du right
			BuildEncryptionCode(node.getRightChild()); // appel par recurrence
		}
		
	}
}
